package order;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import order.util.AESUtils;
import order.util.DESUtils;
import order.util.SignUtil;


import java.util.*;


@Slf4j
public class Demo {

    protected static String getSandboxUrl(String methodUri) {
        return SANDBOX_REQUEST_URL.concat(methodUri);
    }

    private static final String sandboxAppId = "ak1701406951089881088";
    private static final String sandboxAppSecret = "a4C1NboBoExLluMkANsLz";

//    private static final String SANDBOX_REQUEST_URL = "http://127.0.0.1:9330";
    private static final String SANDBOX_REQUEST_URL = "https://openapi-t.fengqiyunsaas.com.cn";


    static String desKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKUfKjKXuXXo5jCccpkDbRIEaRdEUjhTvoy7eGz/FW6TgDsnCTdSnZkfn0hskgqkbvQaJOlay2ZoUjO1xNQIJOA6Gl5CAAcFXlOQ6Wq5iHhig/hf5jSo4VoTE9I3TXTFTk41zr+GRQPT0qrYOBCL6QQ27e3QLqMBPb4VWdNpXqXlAgMBAAECgYAbptdrN4tgWotJ8rkiNLesP77VnaRjOGr9qFtnbWRKazsbLNNXR2eLAAetmjjuvVCzYjlyNrk/QhMaA8OdemuqOFQELvztWnyjnop8NzrwUmOxJzBpnzwxrv76a1xXckgYJt3/KIoyJOR88TUoakVGh12RexDKjaGQLvtcdk91gQJBAM5y4fKSSD7E5aoLyWmBQWA3pwMJhMG6LseDYOXylcQxrG+A/hYtxS9jY91CfEvRlrvqMS6MSeL8jKzrp8+GqsUCQQDMwPf7tcRjO1qnZNrpFozi/qFlaM8q6ydlNQT2OhRh5qtcxk1tKrSrI0M1aUiYURH7Za9qCucpfrURq1HuzEChAkBrfCKpUYHttEPCkdpuZM5t0uvQR/9ngZDjbUJg1jklaZtWfnlLgM7+CigvRXNDYj6xXY/3pTC+zjBLw3GeOYXlAkAbOYU/mLmWICw7mbNpzq/I9uZq33a8VCwWzufr/Wj8Y3lhipR88XK4VqX3Ehqu9giYDrs2NGDsKYbV5JuuTsZBAkEAvgL1TYPw5wIuzuu26058H77D3UwCHygGDVWIFoJ3WShIFRrvNnLPjTlRuWukpghXeX6jo8dLCVuQlWna5oh4oQ==";


    public static String aesIv = "4DE6B7A2B3E90119";
    public static String aesKey = "FE78B8C26F574DE6";


    public static void doWithdraw() {
        //替换成自己的参数
        Map<String, Object> paramMap = new HashMap<>();
        //提交订单  模拟失败 amount 10
        ApiOrderReq apiOrderReq = new ApiOrderReq();
        apiOrderReq.setRequestId(String.valueOf(System.currentTimeMillis()));
        apiOrderReq.setName(AESUtils.encrypt("侯明政", aesKey, aesIv, AESUtils.AES_CFB));
        apiOrderReq.setIdNumber(AESUtils.encrypt("513021199403257552", aesKey, aesIv, AESUtils.AES_CFB));

        apiOrderReq.setAmount(AESUtils.encrypt("1", aesKey, aesIv, AESUtils.AES_CFB));

        apiOrderReq.setAccount(AESUtils.encrypt("18510600676", aesKey, aesIv, AESUtils.AES_CFB));
        apiOrderReq.setMobile(AESUtils.encrypt("18510600676", aesKey, aesIv, AESUtils.AES_CFB));
        apiOrderReq.setBankType(AESUtils.encrypt("ALIPAY", aesKey, aesIv, AESUtils.AES_CFB));
        apiOrderReq.setSalaryType(1);
//        apiOrderReq.setCallbackUrl(AESUtils.encrypt("http://127.0.0.1:8080/api/notify", aesKey, aesIv, AESUtils.AES_CFB));
        paramMap = JSONObject.parseObject(JSONObject.toJSONString(apiOrderReq), Map.class);
        Map<String, Object> result = sendEncryptedRequest("/api/order/receiveOrder", paramMap);
        if ((Boolean) result.get("success")) {
            //data -> {"applyTime":"2025-10-10 14:40:56","orderId":"AOR1976538421403115520","requestId":"1760078452999"}
            // 假设 encryptedData 是你从 result.get("data") 中获取的解密后的字符串
            System.out.println("解密以后的参数data: " + result.get("data"));
            String encryptedData = (String) result.get("data");
            // 使用 FastJSON 解析为 JSONObject
            JSONObject dataJson = JSON.parseObject(encryptedData);
            // 提取各个字段
            String applyTime = dataJson.getString("applyTime");
            String orderId = dataJson.getString("orderId");
            String requestId = dataJson.getString("requestId");

            System.out.println("Apply Time: " + applyTime);
            System.out.println("Order ID: " + orderId);
            System.out.println("Request ID: " + requestId);
            //获取订单状态是否为待支付
            getByRequestId(requestId);


        } else {
            System.out.println("错误信息：" + result.get("message"));
        }
    }

    public static void getByRequestId(String requestId) {
        //根据请求订单号查询结果
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("requestId", requestId);
        Map<String, Object> result = sendEncryptedRequest("/api/order/getByRequestId", paramMap);
        if ((Boolean) result.get("success")) {
            System.out.println("解密以后的参数data: " + result.get("data"));
            String encryptedData = (String) result.get("data");
            // 使用 FastJSON 解析为 JSONObject
            JSONObject dataJson = JSON.parseObject(encryptedData);
            // 提取各个字段
            int status = Integer.parseInt(dataJson.getString("status"));
            String orderId = dataJson.getString("orderId");

            System.out.println("订单状态: " + status);
            System.out.println("Order ID: " + orderId);
            //待支付的订单才允许发起支付
            if (status == 1) {
                confirmPay(orderId);
                //后续调用订单结果查询 获取支付订单结果状态
            }
        } else {
            System.out.println("错误信息：" + result.get("message"));
        }
    }

    public static void main(String ss[]) {
//            getBalance();
//            getByOrderId();
        //作废订单接口
//            cancelOrder();
//            getByRequestId();
        doWithdraw();

//        confirmPay("AOR1977614738502217728");
    }

    public static void getBalance() {
        //获取余额接口
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("requestId", "1760068540095");
        Map<String, Object> result = sendEncryptedRequest("/api/merchant/getBalance", paramMap);
        if ((Boolean) result.get("success")) {
            System.out.println("解密以后的参数data: " + result.get("data"));
        } else {
            System.out.println("错误信息：" + result.get("message"));
        }
    }


    public static void getByOrderId() {
        //根据平台订单号查询结果
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("requestId", "1697699091");
        paramMap.put("orderId", "AOR1976496850146201600");
        Map<String, Object> result = sendEncryptedRequest("/api/order/getByOrderId", paramMap);
        if ((Boolean) result.get("success")) {
            System.out.println("解密以后的参数data: " + result.get("data"));
        } else {
            System.out.println("错误信息：" + result.get("message"));
        }
    }


    public static void confirmPay(String orderId) {
        //确认支付
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("requestId", "1697699091");
        paramMap.put("orderId", orderId);
        Map<String, Object> result = sendEncryptedRequest("/api/order/confirmPay", paramMap);
        if ((Boolean) result.get("success")) {
            System.out.println("解密以后的参数data: " + result.get("data"));
        } else {
            System.out.println("错误信息：" + result.get("message"));
        }
    }


    public static void cancelOrder() {
        //作废订单
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("requestId", "1697699091");
        paramMap.put("orderId", "AOR1976496850146201600");
        Map<String, Object> result = sendEncryptedRequest("/api/order/cancelOrder", paramMap);
        if ((Boolean) result.get("success")) {
            System.out.println("解密以后的参数data: " + result.get("data"));
        } else {
            System.out.println("错误信息：" + result.get("message"));
        }
    }


    public static Map<String, Object> sendEncryptedRequest(String methodUri, Map<String, Object> paramMap) {
        try {
            // 1. 签名和加密
            Map<String, Object> signedParams = SignUtil.wrapMapParams(paramMap, sandboxAppId, sandboxAppSecret);
            String encryptedData = DESUtils.encrypt(desKey, JSON.toJSONString(signedParams));

            // 2. 创建请求
            Request request = new Request.Builder().url(getSandboxUrl(methodUri)).post(new FormBody.Builder().add("data", encryptedData).add("appId", sandboxAppId).build()).build();

            OkHttpClient client = new OkHttpClient();
            try (Response response = client.newCall(request).execute()) {
                if (!response.isSuccessful()) {
                    log.error("HTTP请求失败: code={}, message={}", response.code(), response.message());
                    throw new RuntimeException("HTTP请求失败: " + response.code());
                }

                String responseBody = response.body().string();
                log.debug("原始响应: {}", responseBody);

                JSONObject jsonResponse = JSON.parseObject(responseBody);
                Integer code = jsonResponse.getInteger("code");
                String message = jsonResponse.getString("msg");

                if (code == 0) {
                    String encryptedResult = jsonResponse.getString("data");
                    String decryptedData = DESUtils.decrypt(desKey, encryptedResult);

                    Map<String, Object> result = new HashMap<>();
                    result.put("success", true);
                    result.put("data", decryptedData);
                    return result;
                } else {
                    log.warn("业务处理失败: code={}, message={}", code, message);
                    Map<String, Object> result = new HashMap<>();
                    result.put("success", false);
                    result.put("code", code);
                    result.put("message", message);
                    return result;
                }
            }
        } catch (Exception e) {
            log.error("请求异常", e);
            throw new RuntimeException("请求失败", e);
        }
    }


    public static void signApply() {
        //获取签约URL
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("requestId", "1697699091");


        ConfirmSignContractReq apiOrderReq = new ConfirmSignContractReq();
        apiOrderReq.setRequestId(String.valueOf(System.currentTimeMillis()));
        apiOrderReq.setName(AESUtils.encrypt("侯明政", aesKey, aesIv, AESUtils.AES_CFB));
        apiOrderReq.setIdNumber(AESUtils.encrypt("513021199403257552", aesKey, aesIv, AESUtils.AES_CFB));

        apiOrderReq.setMobile(AESUtils.encrypt("13518376370", aesKey, aesIv, AESUtils.AES_CFB));

        //指定税地需要必传
        apiOrderReq.setBankAccount(AESUtils.encrypt("6228480952235201219", aesKey, aesIv, AESUtils.AES_CFB));

//        //身份证正面  指定税地需要必传
        apiOrderReq.setIdFront("https://****");
//
//        //身份证反面
        apiOrderReq.setIdBackground("https://********");

        paramMap = JSONObject.parseObject(JSONObject.toJSONString(apiOrderReq), Map.class);

        Map<String, Object> result = sendEncryptedRequest("/api/staffContract/signApply", paramMap);
        if ((Boolean) result.get("success")) {
            System.out.println("解密以后的参数data: " + result.get("data"));
        } else {
            System.out.println("错误信息：" + result.get("message"));
        }
    }

    public static void signApplyResult() {
        //获取签约结果
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("requestId", "1697699091");


        ConfirmSignContractReq apiOrderReq = new ConfirmSignContractReq();
        apiOrderReq.setRequestId(String.valueOf(System.currentTimeMillis()));
        apiOrderReq.setName(AESUtils.encrypt("侯明政", aesKey, aesIv, AESUtils.AES_CFB));
        apiOrderReq.setIdNumber(AESUtils.encrypt("513021199403257552", aesKey, aesIv, AESUtils.AES_CFB));


        paramMap = JSONObject.parseObject(JSONObject.toJSONString(apiOrderReq), Map.class);


        Map<String, Object> result = sendEncryptedRequest("/api/staffContract/signApplyResult", paramMap);
        if ((Boolean) result.get("success")) {
            System.out.println("解密以后的参数data: " + result.get("data"));
        } else {
            System.out.println("错误信息：" + result.get("message"));
        }
    }
}